<template>
    <el-dialog :title="title" :visible.sync="open" width="80%" :close-on-click-modal="false" append-to-body :before-close="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="auto" label-position="top">
            <el-form-item label="产品名称" prop="promoteProducts" class="col-md-12">
                <el-input v-model="form.promoteProducts" placeholder="请输入产品名称"/>
            </el-form-item>
            <el-form-item label="渠道名称" prop="channelName" class="col-lg-6">
                <el-input v-model="form.channelName" placeholder="请输入渠道名称"/>
            </el-form-item>
            <el-form-item label="回调比例（默认不修改）" prop="callbackRatio" class="col-lg-6">
                <el-input v-model="form.callbackRatio" placeholder="请输入回调比例（例：100%）"/>
            </el-form-item>
            <el-form-item label="请求链接" prop="sendUrl" class="col-md-12">
                <el-input v-model="form.sendUrl" rows="5" type="textarea" placeholder="请输入请求链接"/>
                <div>
                    <el-button type="success" @click="formatParameters"  size="mini">URL参数格式化</el-button>

                    <i class="el-icon-arrow-down" @click="showParamsBool = !showParamsBool"
                       v-if="showParamsBool">收起参数详情</i>
                    <i class="el-icon-arrow-up" @click="showParamsBool = !showParamsBool" v-else>查看参数详情</i>
                </div>
                <div v-if="showParamsBool">
                    <el-input v-model="item.value" class="col-md-12" v-for="(item, inx) in paramsList" style="margin: 5px 0;">
                        <template slot="prepend">{{ item.key }}</template>
                    </el-input>
                </div>
            </el-form-item>
            <el-form-item label="请求短链" prop="linkName" class="col-lg-6">
                <el-input v-model="form.linkName"  placeholder="请输入请求短链"/>
            </el-form-item>
            <el-form-item label="点击响应（默认不填）" prop="clickResponse" class="col-lg-6">
                <el-input v-model="form.clickResponse"  placeholder="默认不填"/>
            </el-form-item>
            <el-form-item label="回调URL参数（默认不填）" prop="callbackParam" class="col-lg-6">
                <el-input v-model="form.callbackParam"  placeholder="默认不填"/>
            </el-form-item>
            <el-form-item label="回调响应（默认不填）" prop="callbackResponse" class="col-lg-6">
                <el-input v-model="form.callbackResponse"  placeholder="默认不填"/>
            </el-form-item>
            <el-form-item label="ip参数（默认不修改）" prop="ipType" class="col-lg-6">
                <el-input v-model="form.ipType"  placeholder="ip参数：1.tcp取，2.参数中取，3.优先tcp,4.优先参数"/>
            </el-form-item>
            <el-form-item label="ua参数（默认不修改）" prop="uaType" class="col-lg-6">
                <el-input v-model="form.uaType"  placeholder="ua参数：1.http请求头取，2.请求参数取，3.优先http,4.优先参数"/>
            </el-form-item>
            <el-form-item label="链接类型（默认不修改）" prop="linkType" class="col-lg-6">
                <el-input v-model="form.linkType"  placeholder="链接类型：1.IOS,2.andriud"/>
            </el-form-item>
            <el-form-item label="每日点击数（默认不修改）" prop="clickNum" class="col-lg-6">
                <el-input v-model="form.clickNum"  placeholder="默认不修改"/>
            </el-form-item>
            <el-form-item label="每日激活数（默认不修改）" prop="activationNum" class="col-lg-6">
                <el-input v-model="form.activationNum"  placeholder="默认不修改"/>
            </el-form-item>
            <el-form-item label="客户ID（默认不修改）" prop="activationNum" class="col-lg-6">
                <el-input v-model="form.cusId"  placeholder="默认不修改"/>
            </el-form-item>
            <el-form-item label="状态（默认不修改）" prop="activationNum" class="col-lg-6">
                <el-input v-model="form.state"  placeholder="状态：1.正常收发，2.只收不发，3.拒收点击，4.不收不回调，5.暂停使用"/>
            </el-form-item>
            <el-form-item label="素材ID（默认不填）" prop="sourceId" class="col-lg-6">
                <el-input v-model="form.sourceId"  placeholder="默认不填"/>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
</template>

<script>
import {
    add,
    edit,
    findById,
} from "@/api/business/juheAdmin"

export default {
    name: "addOrEdit",
    props: {
        title: {
            type: String
        },
        open: {
            type: Boolean
        },
        type: {
            type: String
        },
        channelId: {
            type: [String, Number]
        },
        randomString: {
            type: String
        }
    },
    data() {
        return {
            form: {
                id: "",
                promoteProducts: "",
                callbackRatio: "100%",
                channelName: "",
                sendUrl: "",
                linkName: "",
                clickResponse: "",
                callbackParam: "",
                callbackResponse: "",
                ipType: "2",
                uaType: "2",
                linkType: "1",
                clickNum: "0",
                activationNum: "0",
                cusId: "6",
                state: "1",
                sourceId: "",
            },
            resetForm: {
                id: "",
                promoteProducts: "",
                callbackRatio: "100%",
                channelName: "",
                sendUrl: "",
                linkName: "",
                clickResponse: "",
                callbackParam: "",
                callbackResponse: "",
                ipType: "2",
                uaType: "2",
                linkType: "1",
                clickNum: "0",
                activationNum: "0",
                cusId: "6",
                state: "1",
                sourceId: "",
            },
            rules: {
                promoteProducts: [ { required: true,message: "请填写产品名称", trigger: 'blur'}],
                callbackRatio: [ { required: true,message: "请填写回调比例", trigger: 'blur'}],
                channelName: [ { required: true,message: "请填写渠道名称", trigger: 'blur'}],
                sendUrl: [ { required: true,message: "请填写请求链接", trigger: 'blur'}],
                linkName: [ { required: true,message: "请填写请求短链", trigger: 'blur'}],
                ipType: [ { required: true,message: "请填写ip参数", trigger: 'blur'}],
                uaType: [ { required: true,message: "请填写ua参数", trigger: 'blur'}],
                linkType: [ { required: true,message: "请填写链接类型", trigger: 'blur'}],
                clickNum: [ { required: true,message: "请填写每日点击数", trigger: 'blur'}],
                activationNum: [ { required: true,message: "请填写每日激活数", trigger: 'blur'}],
                cusId: [ { required: true,message: "请填写客户ID", trigger: 'blur'}],
                state: [ { required: true,message: "请填写状态", trigger: 'blur'}],
            },
            showParamsBool: false,
            paramsList: [],
        }
    },
    computed: {},
    watch: {
        paramsList: {
            handler(newName, oldName) {
                var url = this.form.sendUrl.substring(0, this.form.sendUrl.indexOf("?"))
                var str = "";
                var temp = []
                for (var i = 0; i < this.paramsList.length; i++) {
                    temp.push(this.paramsList[i].key + "=" + this.paramsList[i].value)
                }
                if(url || temp.length>0) {
                    this.form.sendUrl = url + "?" + temp.join("&")
                }
            },
            deep: true,
        },
        randomString: {
            handler(newName, oldName) {
                this.resetParamsList()
                this.init()
            },
            immediate: true,
        }
    },
    mounted() {
    },
    methods: {
        init() {
            if(this.channelId){
                let params = {
                    id: this.channelId,
                    type: this.type
                }
                findById(params).then(res => {
                    Object.keys(this.form).map(key=> {
                        this.$set(this.form, key, res.data.data[key])
                    })
                })
            }else{
                Object.keys(this.form).map(key=> {
                    this.$set(this.form, key, this.resetForm[key])
                })
            }
        },
        resetParamsList() {
            this.paramsList = [];
            this.showParamsBool = false
        },
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if(this.form.id) {
                        edit(this.type ,this.form).then(res=> {
                            this.$message.success("修改成功");
                            this.$emit('update:open', false)
                            this.$emit('getList')
                        }).finally(() => {
                            this.$emit('handleFlushesSingleCache', {id: this.form.id})
                        })
                    }else{
                        let addId;
                        add(this.type ,this.form).then(res=> {
                            this.$message.success("新增成功");
                            this.$emit('update:open', false)
                            this.$emit('getList')
                            addId = res.data.id;
                        }).finally(() => {
                            this.$emit('handleFlushesSingleCache', {id: addId})
                        })
                    }

                }
            })
        },
        cancel() {
            this.$emit('update:open', false)
        },
        formatParameters() {
            let url = this.form.sendUrl
            let temp = [];
            if (url.indexOf("?") != -1 && url.substr(url.indexOf("?") + 1)) {
                var str = url.substr(url.indexOf("?") + 1);
                var strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    temp.push({
                        key: strs[i].split("=")[0],
                        value: unescape(strs[i].split("=")[1])
                    })
                }
            }
            this.$set(this, "paramsList", temp)
            this.showParamsBool = true;
        }
    }
    }
</script>

<style>
.el-form-item .el-select {
    width: 100%;
}

.el-form--label-top .el-form-item__label {
    padding: 0 !important;
}

.el-row {
    margin-bottom: 0px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.el-form--label-top .el-form-item__label {
    float: none;
    display: inline-block;
    text-align: left;
    padding: 0;
}

.col-lg-6 {
    float: left;
    width: 50%;
    padding: 0 10px;
}


.col-md-12 {
    float: left;
    width: 100%;
    padding: 0 10px;
}

.el-dialog__body {
    overflow-y: auto;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}

.el-input-group__prepend {
    width: 200px
}
</style>
